package algorithms.leecode;

public class Au59 {
    public static void main(String[] args) {
        System.err.println(new Au59().generateMatrix(1));
    }
    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        right(0,0,n-1,res,0,n*n);
        ;
        return res;

    }
    public void right(int xIndex,int yIndex,int targetIndex,int[][] res,int current,int max) {
        for(int i = xIndex;i<= targetIndex;i++) {
            res[yIndex][i] = ++current;
        }
        if(current == max) {
            return;
        } else {
            down(targetIndex,yIndex + 1,res.length - 1 - yIndex,res,current,max);
        }
    }
    public void down(int xIndex,int yIndex,int targetIndex,int[][] res,int current,int max) {
        for(int i = yIndex;i<= targetIndex;i++) {
            res[i][xIndex] = ++current;
        }
        if(current == max) {
            return;
        } else {
            left(xIndex - 1,targetIndex ,res.length - 1 - xIndex,res,current,max);
        }
    }
    public void left(int xIndex,int yIndex,int targetIndex,int[][] res,int current,int max) {
        for(int i = xIndex;i >= targetIndex;i--) {
            res[yIndex][i] = ++current;
        }
        if(current == max) {
            return;
        } else {
            up(targetIndex ,yIndex - 1,res.length  - yIndex,res,current,max);
        }
    }
    public void up(int xIndex,int yIndex,int targetIndex,int[][] res,int current,int max) {
        for(int i = yIndex;i >= targetIndex;i--) {
            res[i][xIndex] = ++current;
        }
        if(current == max) {
            return;
        } else {
            right(xIndex + 1,targetIndex,res.length - 1 - xIndex - 1,res,current,max);
        }
    }
}
